//
//  UINavigationController+swizzling.m
//  AppShellTool
//
//  Created by IOS01 on 2022/12/8.
//

#import "UINavigationController+mxswizzling.h"
#import <objc/runtime.h>
#import "ShellLuanchTool.h"

@implementation UINavigationController (swizzling)

+ (void)load{
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        
        [self exchangePopViewController];
        [self exchangePopToRootViewController];
    });
}


+ (void)exchangePopViewController{
    
    SEL originPopSel = @selector(popViewControllerAnimated:);
    SEL overridePopSel = @selector(sf_popViewControllerAnimated:);
    
    Method popViewMethod = class_getInstanceMethod([self class], originPopSel);
    Method sfPopViewMethod = class_getInstanceMethod([self class], overridePopSel);
    
    //原来的类没有实现指定的方法，那么我们就得先做判断，把方法添加进去，然后进行替换
    if (class_addMethod([self class], originPopSel, method_getImplementation(sfPopViewMethod) , method_getTypeEncoding(popViewMethod))) {

        class_replaceMethod([self class],
                            overridePopSel,
                            method_getImplementation(popViewMethod),
                            method_getTypeEncoding(popViewMethod));
    }else{
        //交换实现
        method_exchangeImplementations(popViewMethod, sfPopViewMethod);
    }
}

+ (void)exchangePopToRootViewController{
    SEL originPopSel = @selector(popToRootViewControllerAnimated:);
    SEL overridePopSel = @selector(sf_popToRootViewControllerAnimated:);
    
    Method popViewMethod = class_getInstanceMethod([self class], originPopSel);
    Method sfPopViewMethod = class_getInstanceMethod([self class], overridePopSel);
    
    //原来的类没有实现指定的方法，那么我们就得先做判断，把方法添加进去，然后进行替换
    if (class_addMethod([self class], originPopSel, method_getImplementation(sfPopViewMethod) , method_getTypeEncoding(popViewMethod))) {

        class_replaceMethod([self class],
                            overridePopSel,
                            method_getImplementation(popViewMethod),
                            method_getTypeEncoding(popViewMethod));
    }else{
        //交换实现
        method_exchangeImplementations(popViewMethod, sfPopViewMethod);
    }
}


/// 替换弹出
/// @param animated animated description
- (void)sf_popViewControllerAnimated:(BOOL)animated{
    NSLog(@"%i",self.viewControllers.count);
    if ([[ShellLuanchTool shareTool] isCanOutApllication]) {
        [[ShellLuanchTool shareTool] shellIsBack];
    }else{
        [self sf_popViewControllerAnimated:animated];
    }
}


/// 替换弹到根控制器
/// @param animated animated description
- (void)sf_popToRootViewControllerAnimated:(BOOL)animated{
    if ([[ShellLuanchTool shareTool] isCanOutApllication]) {
        [[ShellLuanchTool shareTool] shellIsBack];
    }else{
        [self sf_popToRootViewControllerAnimated:animated];
    }
}


@end
